package com.icehand.demo.service.strategy;

import cn.hutool.core.lang.ClassScaner;
import com.google.common.collect.Maps;
import com.icehand.demo.service.strategy.annonation.OrderHandlerType;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class OrderHandlerProcessor implements BeanFactoryPostProcessor {
    @Value("${order.handler.packaget}")
    private String OrderHandlerPackageName;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<Integer, Class> handlerMap = Maps.newHashMapWithExpectedSize(3);
        ClassScaner.scanPackageByAnnotation(OrderHandlerPackageName, OrderHandlerType.class).forEach(c -> {
            int type = c.getAnnotation(OrderHandlerType.class).type().getType();
            handlerMap.put(type,c);
        });
        OrderHandlerContext orderHandlerContext = new OrderHandlerContext(handlerMap);
        configurableListableBeanFactory.registerSingleton(orderHandlerContext.getClass().getName(),orderHandlerContext);
    }
}
